import TagGroup from '@/components/TagGroup';
import TextEditor from '@/pages/cues/components/TextEditor';
import UploadDragger from '@/pages/cues/components/UploadDragger';
import {
  initSaveActiveTreeAssignOrganization,
  saveCuesActive,
} from '@/services/api/api-cues-active';
import { listCuesIndustry } from '@/services/api/api-cues-industry';
import { CheckCircleTwoTone, FileSearchOutlined, SendOutlined } from '@ant-design/icons';
import { ModalForm, ProCard, ProFormCascader } from '@ant-design/pro-components';
import ProForm, {
  DrawerForm,
  ProFormInstance,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-form';
import { ActionType } from '@ant-design/pro-table';
import { Button, Card, Cascader, Form, message } from 'antd';
import Meta from 'antd/es/card/Meta';
import FormItem from 'antd/es/form/FormItem';
import { DefaultOptionType } from 'antd/es/select';
import { DataNode } from 'antd/es/tree';
import 'dayjs/locale/zh-cn';
import React, { useRef, useState } from 'react';
import { useAccess } from 'umi';
import AddActivePreview from './AddActivePreview';
interface wordImportProps {
  onRefurbish: () => void;
}
const WordImport: React.FC<wordImportProps> = ({ onRefurbish }) => {
  const access = useAccess();

  const actionRef = useRef<ActionType>();

  const formRef = useRef<ProFormInstance>();
  const ModalFormformRef = useRef<ProFormInstance>();

  const [industrys, setIndustrysState] = useState<any[]>([]);

  const [openAddActive, setOpenAddActive] = useState<boolean>();
  const [textEditorContent, setTextEditorContentState] = useState();

  const [openAddActivePreview, setOpenAddActivePreview] = useState<boolean>(false);
  const [previewData, setPreviewData] = useState<CuesActiveBo.AddActivePreview>();

  const [modalFormOpen, setModalFormOpenState] = useState<boolean>(false);

  /**
   * 推送单位数据
   */
  const [treeAssignOrganizationData, setTreeAssignOrganizationDataState] = useState<DataNode[]>();

  /**
   * 预备Tree结构数据
   * @param data
   */
  function readyTreeData(data: AdminOrganizationData.Organization[]): any {
    const treeData = new Array();
    if (data) {
      data.forEach((val) => {
        treeData.push({
          label: val.name,
          value: val.id,
          disabled: val.isFolder === 1 && val.isOrganization === 0 && val.children === undefined  ,        children: readyTreeData(val.children as AdminOrganizationData.Organization[]),
        });
      });
    }
    return treeData;
  }

  /**
   * 加载 保存 推送 单位
   */
  const loadInitSaveActiveTreeAssignOrganization = async () => {
    try {
      const response = await initSaveActiveTreeAssignOrganization();
      if (response.code === 0) {
        setTreeAssignOrganizationDataState(readyTreeData(response.data));
      }
    } catch (error) {}
  };

  /**
   * 加载权限详情
   * @param key
   */
  const getCuesIndustryData = async () => {
    try {
      const response = await listCuesIndustry();

      setIndustrysState(
        response.data.map((item) => {
          return { label: item.name, value: item.id };
        }),
      );
    } catch (error) {}
  };

  /**
   * 级联组件 搜索筛选
   * @param inputValue
   * @param path
   * @returns
   */
  const filter = (inputValue: string, path: DefaultOptionType[]) =>
    path.some(
      (option) => (option.label as string).toLowerCase().indexOf(inputValue.toLowerCase()) > -1,
    );

  return (
    <>
      <ModalForm<{
        content: '';
      }>
        title="word导入"
        trigger={
          <Card
            hoverable
            bordered={false}
            style={{ width: 130, marginTop: 10, backgroundColor: '#ffe58f' }}
            // onClick={() => setShowListState(!showList)}
            // cover={<img alt="example" src={cuesImage} />}
          >
            <Meta title="word导入" />
          </Card>
        }
        formRef={ModalFormformRef}
        autoFocusFirstInput
        modalProps={{
          destroyOnClose: true,
          onCancel: () => console.log('run'),
        }}
        // submitter={{
        //     render: (props,defaultDoms) => {
        //         const values = formRef.current?.getFieldsValue();
        //         return [
        //             ...defaultDoms,
        //             <AddActive
        //                 key="add_active"
        //                 onRefurbish={() => {
        //                     // const values = formRef.current?.getFieldsValue();
        //                     // console.log(values);
        //                 }}
        //                 triggerMode='title'
        //             />
        //         ];
        //     },
        // }}
        onFinish={async (values) => {
          console.log(values.content);
          setTextEditorContentState(values.content);
          setOpenAddActive(true);

          message.success('提交成功');
          return true;
        }}
      >
        <FormItem
          name="content"
          hidden={!access.线索征集x报送线索x附件}
          label={
            <span
              style={{
                marginLeft: 11,
              }}
            >
              线索内容
            </span>
          }
        >
          <TextEditor
            onInit={(editor) => {}}
            readonly={false}
            onClick={(value) => {}}
            defaultContent=""
            tinyID="tinyId"
          />
        </FormItem>
      </ModalForm>
      <DrawerForm
        key="drawer_form_add_submit"
        title="报送线索"
        drawerProps={{
          maskClosable: false,
          destroyOnClose: true,
          width: 1150,
        }}
        formRef={formRef}
        initialValues={{}}
        open={openAddActive}
        onOpenChange={(visible) => {
          setOpenAddActive(visible);
          if (visible) {
            console.log(textEditorContent);
            formRef.current?.setFieldsValue({
              articleContent: textEditorContent,
            });
            getCuesIndustryData();
            loadInitSaveActiveTreeAssignOrganization();
          } else {
            setTreeAssignOrganizationDataState([]);
          }
        }}
        layout="horizontal"
        submitter={{
          searchConfig: {
            submitText: (
              <>
                <FileSearchOutlined /> 预览
              </>
            ),
          },
          render: (props, defaultDoms) => {
            return [
              defaultDoms,
              <AddActivePreview
                key="add_active_preview"
                onSubmit={() => {
                  setOpenAddActive(false);
                }}
                open={openAddActivePreview}
                onOpenChange={(open) => {
                  setOpenAddActivePreview(open);
                }}
                details={previewData}
              />,
              <Button
                key="button_add_submit"
                icon={<SendOutlined />}
                type="primary"
                style={{
                  background: '#87d068',
                }}
                onClick={() => {
                  /**
                   * ======================
                   * 直接发布
                   * ======================
                   */
                  const values = formRef.current?.getFieldsValue();

                  if (!(values.articleName !== undefined && values.articleName.length > 0)) {
                    message.warning('请输入标题');
                    return;
                  }

                  if (
                    !(
                      values.articleIndustryIds !== undefined &&
                      values.articleIndustryIds.length > 0
                    )
                  ) {
                    message.warning('请选择至少一个选题方向');
                    return;
                  }

                  if (!(values.articleLabels !== undefined && values.articleLabels.length > 0)) {
                    message.warning('请输入至少一个标签');
                    return;
                  }

                  if (!(values.articleContent !== undefined && values.articleContent.length > 0)) {
                    message.warning('请输入线索内容');
                    return;
                  }

                  setModalFormOpenState(true);
                }}
              >
                提交
              </Button>,
              <ModalForm
                key={'modal_form_add_submit'}
                title={
                  <>
                    <CheckCircleTwoTone
                      style={{
                        marginRight: 8,
                      }}
                      twoToneColor="#87d068"
                    />
                    确认提交
                  </>
                }
                autoFocusFirstInput
                modalProps={{
                  width: 400,
                  destroyOnClose: true,
                }}
                open={modalFormOpen}
                onOpenChange={setModalFormOpenState}
                submitTimeout={2000}
                submitter={{
                  submitButtonProps: {
                    type: 'primary',
                    style: { background: '#87d068' },
                  },
                }}
                onFinish={async () => {
                  const values = formRef.current?.getFieldsValue();

                  if (
                    values.articleAttachments !== undefined &&
                    values.articleAttachments.length > 0
                  ) {
                    const articleAttachments = values.articleAttachments.map(
                      (item: { response: { data: { id: any } } }) => {
                        return item.response.data.id;
                      },
                    );

                    values.articleAttachments = articleAttachments;
                  }

                  const response = await saveCuesActive({
                    articleName: values?.articleName,
                    articleIndustryIds: values?.articleIndustryIds,
                    articleLabels: values?.articleLabels,
                    remarks: values?.remarks,
                    assignOrganizationIds: values?.assignOrganizationIds,
                    articleContent: values?.articleContent,
                    articleAttachments: values.articleAttachments,
                    createdSource: 1,
                  });

                  if (response.code === 0) {
                    message.success('提交成功');
                    onRefurbish();
                    setOpenAddActive(false);
                    return true;
                  } else {
                    return false;
                  }
                }}
              />,
            ];
          },
        }}
        onFinish={async (values) => {
          if (
            values.articleName === undefined ||
            values.articleName.length === 0 ||
            values.articleName.trim() === ''
          ) {
            message.warning('请输入标题');
            return;
          }

          if (values.articleIndustryIds === undefined || values.articleIndustryIds.length === 0) {
            message.warning('请选择最少一个行业');
            return;
          }

          if (values.articleLabels === undefined || values.articleLabels.length === 0) {
            message.warning('请输入最少一个标签');
            return;
          }

          if (
            values.articleContent === undefined ||
            values.articleContent.length === 0 ||
            values.articleContent.trim() === ''
          ) {
            message.warning('请输入线索内容');
            return;
          }

          const articleIndustrys = values.articleIndustryIds?.map((item) => {
            const industry = industrys.find((e) => e.value === item);
            return industry;
          });

          setPreviewData({
            articleName: values.articleName,
            articleIndustrys: articleIndustrys,
            articleLabels: values.articleLabels,
            remarks: values.remarks,
            assignOrganizationIds: values.assignOrganizationIds,
            articleContent: values.articleContent,
            articleAttachments: values.articleAttachments,
            createdSource: 1,
            showTreeAssignOrganizationData: treeAssignOrganizationData,
          });

          setOpenAddActivePreview(true);
        }}
      >
        <ProFormText
          width="xl"
          name="articleName"
          label={
            <>
              <span
                style={{
                  color: '#ff4d4f',
                  fontSize: 14,
                  paddingRight: 4,
                }}
              >
                *
              </span>
              标题
            </>
          }
          fieldProps={{
            allowClear: true,
            maxLength: 200,
          }}
        />
        <ProFormSelect
          width="xl"
          name="articleIndustryIds"
          label={
            <>
              <span
                style={{
                  color: '#ff4d4f',
                  fontSize: 14,
                  paddingRight: 4,
                }}
              >
                *
              </span>
              行业
            </>
          }
          options={industrys}
          fieldProps={{
            mode: 'multiple',
            allowClear: true,
          }}
          extra={'最少输入一个'}
        />
        <Form.Item
          label={
            <>
              <span
                style={{
                  color: '#ff4d4f',
                  fontSize: 14,
                  paddingRight: 4,
                }}
              >
                *
              </span>
              标签
            </>
          }
          name="articleLabels"
          extra={'最少输入一个'}
        >
          <TagGroup
            style={{
              marginLeft: '28px',
            }}
          />
        </Form.Item>
        <ProFormCascader
          width="xl"
          label={
            <span
              style={{
                marginLeft: 11,
              }}
            >
              报送
            </span>
          }
          name="assignOrganizationIds"
          placeholder="选择媒体"
          extra="不选择，默认推送给所有媒体单位"
          fieldProps={{
            options: treeAssignOrganizationData,
            showSearch: { filter },
            multiple: true,
            removeIcon: true,
            allowClear: true,
            maxTagCount: 'responsive',
            showCheckedStrategy: Cascader.SHOW_CHILD,
          }}
        />
        <ProForm.Group>
          <ProFormTextArea
            name="remarks"
            label={
              <span
                style={{
                  marginLeft: 11,
                }}
              >
                备注
              </span>
            }
            width="xl"
            fieldProps={{
              allowClear: true,
              rows: 3,
              maxLength: 200,
            }}
          />
        </ProForm.Group>
        <ProCard ghost>
          <ProCard ghost>
            <ProForm.Item
              name="articleContent"
              label={
                <>
                  <span
                    style={{
                      color: '#ff4d4f',
                      fontSize: 14,
                      paddingRight: 4,
                    }}
                  >
                    *
                  </span>
                  线索内容
                </>
              }
            >
              {treeAssignOrganizationData ? (
                <TextEditor
                  onInit={(editor) => {}}
                  readonly={false}
                  onClick={(value) => {}}
                  defaultContent=""
                  tinyID="tinyId1"
                />
              ) : (
                <></>
              )}
            </ProForm.Item>
          </ProCard>
        </ProCard>
        <FormItem
          name="articleAttachments"
          hidden={!access.主动报送x报送线索x附件}
          label={
            <span
              style={{
                marginLeft: 11,
              }}
            >
              附件
            </span>
          }
        >
          <UploadDragger
            onPreview={(file) => {}}
            access={{
              isPicture: access.主动报送x报送线索x附件x图片,
              isVideo: access.主动报送x报送线索x附件x视频,
              isOffice: access.主动报送x报送线索x附件x办公,
              isOther: access.主动报送x报送线索x附件x其他,
            }}
            url="/cues/attachment/save"
            mode="active"
          />
        </FormItem>
      </DrawerForm>
    </>
  );
};
export default WordImport;
